package com.easwift.qsp.das.qjy;

import com.easwift.qsp.enums.DeviceTypeEnum;
import com.easwift.qsp.enums.MonitorItemEnum;
import com.easwift.qsp.util.BitUtils;
import com.easwift.qsp.util.DataSourceUtils;
import com.easwift.qsp.util.LogUtils;

import java.io.BufferedInputStream;

/**
 * 倾角仪读数据线程
 * @author Administrator
 *
 */
public class QJYSocketReadThread extends Thread{

	private BufferedInputStream bis;

	public QJYSocketReadThread(BufferedInputStream bis) {
		super();
		this.bis = bis;
	}

	@Override
	public void run(){
		try{
			while(true){
				if(bis.available() != 0){
					byte[] bytes = new byte[bis.available()];
					bis.read(bytes,0,bis.available());
					System.out.print("端口8092读取到数据：");
					LogUtils.printFrame(bytes);
					//如果数据不符合要求不处理
					if(bytes.length==24){
						//设备地址
						int address = Byte.toUnsignedInt(bytes[0]) + (Byte.toUnsignedInt(bytes[1]) << 8);
						//X方向角度
						double x = 0;
						//Y方向角度
						double y = 0;

						byte[] bbs = new byte[4];

						System.arraycopy(bytes,14,bbs,0,4);
						bbs = BitUtils.reverseArray(bbs);
						x= BitUtils.byteArrayToFloat(bbs);

						System.arraycopy(bytes,18,bbs,0,4);
						bbs = BitUtils.reverseArray(bbs);
						y = BitUtils.byteArrayToFloat(bbs);

						System.out.println(String.format("X方向角度：%s",x));
						System.out.println(String.format("Y方向角度：%s",y));

						String sql = String.format("insert into tb_device_qjdata (address,x,y,createtime) values (%s,%s,%s,%s)",String.valueOf(address),x,y,"now()");
						DataSourceUtils.getJdbcTemplate().execute(sql);

					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
